/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        int ans = 0;
        dfs(root, ans);
        return ans;
    }

    int dfs(TreeNode* node, int& ans)
    {
        if (node == nullptr)
            return -1;
        int l_len = dfs(node->left, ans); // 左子树最大链长
        int r_len = dfs(node->right, ans); // 右子树最大链长

        ans = max(ans, l_len + r_len + 2); // 两条链拼成路径，当节点为叶子时，-1 + -1 + 2 = 0
        return max(l_len, r_len) + 1; // 当前子树最大链长 + 1
    }
};